<!-- 定标结果确认 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="purchaseBill">
          <u--input v-model="model.purchaseBill" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="proposer">
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="departId">
          <h-select-depart-input
            v-model="model.departId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime">
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="领用团队" prop="teamId" required>
          <h-select-team-input
            style="width: 100%"
            v-model="model.teamId"
            objectField="model.teamId"
            placeholder="请选择领用团队"
            border="surround"
            :tdlx="3"
          />
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea confirm-type="send" maxlength="500" v-model="model.remark" placeholder="请输入备注"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">物品领用明细</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="handleAddMaterial">新增</u-button>
        </view>

        <u-collapse>
          <u-collapse-item :title="`物品领用明细表单${index + 1}`" v-for="(item, index) in formData" :key="index">
            <FormInfo
              :provisionBroad="model.provisionBroad"
              :item="item"
              :index="index"
              @edit="handleEditForm"
              @remove="handleRemoveForm"
              @copy="handleCopyForm"
            />
          </u-collapse-item>
        </u-collapse>
        <u-popup class="form-popup" mode="right" :show="showFormModal" @close="closeFormModal" @open="openFormModal">
          <MaterialForm
            ref="dataForm"
            :provisionBroad="model.provisionBroad"
            :index="index"
            @submit="handleFormSubmit"
            @close="showFormModal = false"
          />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.purchaseFile" :isIcon="false"></h-upload-file>
          <file-list v-if="model.purchaseFile" v-model="model.purchaseFile" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="space-x-1 mt-1 px-1 pb-1" style="display: flex">
        <u-button type="primary" text="保存提交" :loading="loading" @click="onSubmit"></u-button>
        <u-button type="primary" text="保存草稿" :loading="loading" @click="onDraft"></u-button>
      </view>
    </u-form>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, info } from '@/api/hr/ErpPurchaseRecipientsForm'

import fileList from '@/pages/synergy/components/fileList.vue'
import MaterialForm from './components/MaterialForm.vue'
import FormInfo from './components/MaterialFormInfo.vue'
export default {
  name: 'ErpPurchaseRecipientsForm',
  components: {
    fileList,
    MaterialForm,
    FormInfo,
  },
  data() {
    return {
      backUpProvisionBroad: '',
      showBusinessSegment: false,
      exportTeamId: '',
      flag: false,
      index: null,
      showFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      dataSource2: [],
      basicForm: {},
      // formData: [
      //   {
      //     id: 411283512599,
      //     materialBillId: 'WL01343',
      //     brand: '农夫山泉',
      //     specification: '6L',
      //     amount: '6',
      //     provisionSmall: '1535177002383859714',
      //     materialName: '1627503793494896641',
      //     referencePrice: null,
      //     unit: '4',
      //     budgetAmount: '12',
      //   },
      // ],
      formData: [],
      model: {
        purchaseBill: '',
        proposer: '',
        departId: '',
        createTime: '',
        teamId: '',
        remark: '',
        purchaseFile: null,
      },
      rules: {
        purchaseBill: [{ required: true, message: '单据编号不能为空!', trigger: 'blur' }],
        teamId: [{ required: true, message: '请选择领用团队!', trigger: 'change' }],
      },
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
      this.initBillNo()
    }
    // this.initBuyerInfo()
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    /**
     * 弹窗点击确认
     */
    handleConfirmModalConfirm() {
      this.formData = []
      this.confirmModal = false
    },
    /**
     * 弹窗点击取消
     */
    handleConfirmModalCancel() {
      // 还原修改的数据
      if (this.resetKey) {
        let realKey = this.resetKey.replace('backUp', '')
        realKey = realKey[0].toLowerCase() + realKey.slice(1)
        this.isReset = true
        this.$set(this.model, realKey, this[this.resetKey])
        setTimeout(() => (this.isReset = false), 0)
      }
      this.confirmModal = false
    },
    /**
     * 修改值时，检查是否需要弹出对话框确认修改
     * 取消 modal 的时候，需要将值还原
     * @param {String} key BasicForm 中的key值
     * @param {Function} fn 回调函数
     * @param {any} data 回调函数参数
     */
    checkSwitch(key, fn, data) {
      this.$nextTick(() => {
        if (this.isReset) return
        const firstChar = key[0].toUpperCase()
        key = firstChar + key.slice(1)
        const oldData = this[`backUp${key}`]
        if (oldData && oldData !== this.model[key]) {
          this.confirmModal = true
          this.resetKey = `backUp${key}`
        } else {
          fn && fn(data)
        }
      })
    },
    projectChange() {},
    handleChangeFoldTeamId(val, num = 0) {
      let v = val.id
      this.foldTeamIdChange(v, num)
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    foldTeamIdChange(id, edit) {
      if (this.model.exportTeamId == id) {
        this.$u.toast('调入团队不能和调出团队相同')
        this.$set(this.model, 'foldTeamId', null)
        this.$set(this.model, 'foldWarehouse', undefined)
        return false
      }
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.foldWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'foldWarehouse', undefined)
          }
          const data = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.foldWarehouseList = [data]
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 新增物料
    handleAddMaterial() {
      this.index = null
      this.showFormModal = true
    },
    handleChangeExportTeamId(v, num = 0) {
      if (v != this.exportTeamId) {
        this.exportTeamIdChange(v, num)
      }
      this.exportTeamId = this.model.exportTeamId
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    exportTeamIdChange(row, edit = false) {
      const id = row.id
      if (this.model.foldTeamId == id) {
        this.model.exportTeamId = this.exportTeamId
        this.$u.toast('调入团队不能和调出团队相同')
        return false
      }
      // 清空子表
      // this.$refs.cannibalizeDetailList.reset()
      this.warehouse = null
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.exportWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'exportWarehouse', undefined)
            this.warehouse = null
          }
          const list = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.exportWarehouseList = [list]
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
      // this.initBuyerInfo()
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo()
      this.model.purchaseBill = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.purchaseBill //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.departId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      for (const key in data) {
        if (Object.hasOwnProperty.call(this.model, key)) {
          this.model[key] = data[key]
        }
      }
    },
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (this.model.projectBudget >= 10000) {
          this.$u.toast('当前采购总金额大于等于10000元，请走招标采购申请单！')
          return Promise.reject('当前采购总金额大于等于10000元，请走招标采购申请单！')
        }
        if (!this.formData.length) {
          this.$u.toast('请添加物资明细信息！')
          return Promise.reject('请添加物资明细信息！')
        }
        return Promise.resolve()
      })
    },
    async onSubmit() {
      await this.validateForm()

      try {
        this.loading = true
        const response = await add({
          ...this.model,
          detailList: this.formData,
        })
        this.$u.toast(response.message)
        if (response.success) {
          setTimeout(
            () =>
              uni.switchTab({
                url: '/pages/home/home',
              }),
            1500,
          )
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
      await this.validateForm()
    },
  },
  watch: {
    tenderFormData: {
      immediate: true,
      handler(val) {
        if (val?.length) {
          const total = val.reduce((total, item) => {
            return total + item.amount * item.budgetAmount
          }, 0)
          this.$set(this.model, 'projectBudget', String(total))
        } else {
          this.$set(this.model, 'projectBudget', String(0))
        }
      },
    },
    'model.provisionBroad'(current, old) {
      if (old && current && old !== current) {
        this.backUpProvisionBroad = old
      }
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
